"""
自定义分页组件:
一、在视图函数中:
导入类:
from ***.Pagination import Pagination

def list(request):

    # 1.根据自己的情况去筛选需要的数据
    queryset = models.List.objects.all()

    # 2.实例化分页对象
    page_object = Pagination(request,queryset)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  #生成页码
    }

    return render(request,"list.html",context)

二、在HTML页面中
<tbody>
    {% for object in queryset %}
        <tr>
            <th scope="row">{{object.xxx}}</th>
            <td>{{object.xxx}}</td>
            ...
        </tr>
    {% endfor %}
</tbody>

...

<nav aria-label="Page navigation">
    <ul class="pagination">
        {{page_string}}
    </ul>
</nav>

"""

from django.utils.safestring import mark_safe
import copy


class Pagination(object):

    def __init__(self, request, queryset, page_size=10, page_param="page", plus=5):
        """
        :param request: 请求的对象
        :param queryset: 符号条件的数据(根据这个数据给他进行分页处理)
        :param page_size: 每页显示多少条数据
        :param page_param: 在URL中传递的参数,例如:?page=9
        :param plus: 显示当前页的 前或后几页
        """
        # 获取参数page的值，若没有则默认为 1
        self.page_param = page_param
        page = request.GET.get(page_param, "1")

        # 如果输入的参数page的值不是数字，则默认为 1
        if page.isdecimal():
            page = int(page)
        else:
            page = 1

        # page为参数page的值
        # page_size为每页显示的数据条数
        self.page = page
        self.page_size = page_size

        # 起始页码，终止页码
        self.start = (page - 1) * page_size
        self.end = page * page_size

        # 对数据进行切片分割，获取指定条数
        self.page_queryset = queryset[self.start: self.end]

        # 获取数据的总条数
        total_count = queryset.count()

        # 获取页面总页数
        total_page_count, div = divmod(total_count, page_size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

        # 获取GET请求里携带的所有参数.用于参数拼接:self.query_dict.urlencode()
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict

    def html(self):
        # a.计算出显示当前页的前5页and后5页
            # -数据库中数据比较少，没有达到11项
        if self.total_page_count <= 2 * self.plus + 1:
            start_page = 1
            end_page = self.total_page_count
            # -数据库中数据比较多，大于11项
        else:
                # --当前页page<5时（小极值）
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus + 1
            else:
                # --当前页page>5
                    # ---当前页+5 > 总页数
                if (self.page+self.plus) > self.total_page_count:
                    start_page = self.total_page_count - 2 * self.plus
                    end_page = self.total_page_count
                    # ---当前页+5 < 总页数
                else:
                    start_page = self.page-self.plus
                    end_page = self.page+self.plus
        
        page_str_list = []  # 装html代码

        # b.首页
        self.query_dict.setlist(self.page_param,[1])
        page_str_list.append('<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode()))

        # c.上一页
        if self.page>1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev='<li><a href="?{}"><span aria-hidden="true">&laquo;</span></a></li>'.format(self.query_dict.urlencode())
        else:
            prev='<li class="disabled"><span aria-hidden="true">&laquo;</span></li>'
        page_str_list.append(prev)

        # d.页面
        for i in range(start_page,end_page+1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = '<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            else:
                ele = '<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            page_str_list.append(ele)

        # 下一页
        if self.page<self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page+1])
            prev='<li><a href="?{}"><span aria-hidden="true">&raquo;</span></a></li>'.format(self.query_dict.urlencode())
        else:
            prev='<li class="disabled"><span aria-hidden="true">&raquo;</span></li>'
        page_str_list.append(prev)

        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        page_str_list.append('<li><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))

        # 跳转
        # search_string = """
        # 略...
        # """

        # mark_safe()没有这个的话，页面会直接显示html代码
        # page_str_list里的html代码拼接成一串字符串，并返回
        page_string = mark_safe("".join(page_str_list))
        return page_string

